using System;
using System.Text;

namespace Game.Network {
    public class PacketReader {
        private byte[] m_data;
        private int m_length;
        private int m_pos;

        public PacketReader (byte[] data, bool fixedLength) {
            m_data = data;
            m_length = data.Length;
            m_pos = fixedLength ? 1 : 3;
        }

        public sbyte ReadSByte () {
            if ((m_pos + 1) > m_length)
                return 0;
            
            return (sbyte)m_data [m_pos++];
        }

        public short ReadInt16 () {
            if ((m_pos + 2) > m_length)
                return 0;
            
            return (short)((m_data [m_pos++] << 8) | m_data [m_pos++]);
        }

        public int ReadInt32 () {
            if ((m_pos + 4) > m_length)
                return 0;

            return (m_data [m_pos++] << 24)
                | (m_data [m_pos++] << 16)
                | (m_data [m_pos++] << 8)
                | m_data [m_pos++];
        }

        public byte ReadByte () {
            if ((m_pos + 1) > m_length)
                return 0;
            
            return m_data [m_pos++];
        }

        public ushort ReadUInt16 () {
            if ((m_pos + 2) > m_length)
                return 0;
            
            return (ushort)((m_data [m_pos++] << 8) | m_data [m_pos++]);
        }
        
        public uint ReadUInt32 () {
            if ((m_pos + 4) > m_length)
                return 0;
            
            return (uint)((m_data [m_pos++] << 24)
                | (m_data [m_pos++] << 16)
                | (m_data [m_pos++] << 8)
                | m_data [m_pos++]);
        }

        public bool ReadBool () {
            if ((m_pos + 1) > m_length)
                return false;
            
            return m_data [m_pos++] == 1;
        }

        public string ReadAsciiPString () {
            int length = ReadByte ();
            if ((m_pos + length) > m_length)
                return "";

            string res = Encoding.ASCII.GetString (m_data, m_pos, length);
            m_pos += length;
            return res;
        }
    }
}

